//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.jim.server.protocol.ws;

import java.nio.ByteBuffer;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig.Global;
import org.jim.core.packets.ChatBody;
import org.jim.core.ws.IWsMsgHandler;
import org.jim.core.ws.Opcode;
import org.jim.core.ws.WsConfig;
import org.jim.core.ws.WsRequestPacket;
import org.jim.core.ws.WsResponsePacket;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.protocol.ProtocolManager.Packet;
import org.jim.server.util.ChatKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WsMsgHandler implements IWsMsgHandler {
	private static Logger log = LoggerFactory.getLogger(WsMsgHandler.class);
	private WsConfig wsServerConfig;

	public Object onText(WsRequestPacket wsRequestPacket, String text, ImChannelContext imChannelContext) throws Exception {
		ChatBody chatBody = ChatKit.toChatBody(wsRequestPacket.getBody(), imChannelContext);
		ImServerConfig imServerConfig = (ImServerConfig)Global.get();
		boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
		String toId = chatBody.getToId();
		ImPacket sendSuccessPacket;
		if (ChatKit.isOnline(toId, isStore)) {
			JimServerAPI.sendToUser(toId, wsRequestPacket);
			sendSuccessPacket = Packet.success(imChannelContext);
			text = new String(sendSuccessPacket.getBody(), "utf-8");
		} else {
			sendSuccessPacket = Packet.offline(imChannelContext);
			text = new String(sendSuccessPacket.getBody(), "utf-8");
		}

		return text;
	}

	public Object onBytes(WsRequestPacket webSocketPacket, byte[] bytes, ImChannelContext imChannelContext) throws Exception {
		String text = new String(bytes, "utf-8");
		log.info("收到byte消息:{},{}", bytes, text);
		ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
		buffer.put(bytes);
		return buffer;
	}

	public WsResponsePacket handler(ImPacket imPacket, ImChannelContext imChannelContext) throws Exception {
		WsRequestPacket wsRequest = (WsRequestPacket)imPacket;
		return this.h(wsRequest, wsRequest.getBody(), wsRequest.getWsOpcode(), imChannelContext);
	}

	public WsResponsePacket h(WsRequestPacket wsRequest, byte[] bytes, Opcode opcode, ImChannelContext imChannelContext) throws Exception {
		WsResponsePacket wsResponse = null;
		if (opcode == Opcode.TEXT) {
			if (bytes != null && bytes.length != 0) {
				String text = new String(bytes, this.wsServerConfig.getCharset());
				Object retObj = this.onText(wsRequest, text, imChannelContext);
				String methodName = "onText";
				wsResponse = this.processRetObj(retObj, methodName, imChannelContext);
				return wsResponse;
			} else {
				JimServerAPI.remove(imChannelContext, "错误的webSocket包，body为空");
				return null;
			}
		} else {
			Object retObj;
			String methodName;
			if (opcode == Opcode.BINARY) {
				if (bytes != null && bytes.length != 0) {
					retObj = this.onBytes(wsRequest, bytes, imChannelContext);
					methodName = "onBytes";
					wsResponse = this.processRetObj(retObj, methodName, imChannelContext);
					return wsResponse;
				} else {
					JimServerAPI.remove(imChannelContext, "错误的webSocket包，body为空");
					return null;
				}
			} else if (opcode != Opcode.PING && opcode != Opcode.PONG) {
				if (opcode == Opcode.CLOSE) {
					retObj = this.onClose(wsRequest, bytes, imChannelContext);
					methodName = "onClose";
					wsResponse = this.processRetObj(retObj, methodName, imChannelContext);
					return wsResponse;
				} else {
					JimServerAPI.remove(imChannelContext, "错误的webSocket包，错误的Opcode");
					return null;
				}
			} else {
				log.error("收到" + opcode);
				return null;
			}
		}
	}

	private WsResponsePacket processRetObj(Object obj, String methodName, ImChannelContext imChannelContext) throws Exception {
		if (obj == null) {
			return null;
		} else {
			WsResponsePacket wsResponse;
			if (obj instanceof String) {
				String str = (String)obj;
				wsResponse = new WsResponsePacket();
				wsResponse.setBody(str.getBytes(this.wsServerConfig.getCharset()));
				wsResponse.setWsOpcode(Opcode.TEXT);
				return wsResponse;
			} else if (obj instanceof byte[]) {
				wsResponse = new WsResponsePacket();
				wsResponse.setBody((byte[])((byte[])obj));
				wsResponse.setWsOpcode(Opcode.BINARY);
				return wsResponse;
			} else if (obj instanceof WsResponsePacket) {
				return (WsResponsePacket)obj;
			} else if (obj instanceof ByteBuffer) {
				wsResponse = new WsResponsePacket();
				byte[] bs = ((ByteBuffer)obj).array();
				wsResponse.setBody(bs);
				wsResponse.setWsOpcode(Opcode.BINARY);
				return wsResponse;
			} else {
				log.error("{} {}.{}()方法，只允许返回byte[]、ByteBuffer、WebSocketResponsePacket或null，但是程序返回了{}", new Object[]{imChannelContext, this.getClass().getName(), methodName, obj.getClass().getName()});
				return null;
			}
		}
	}

	public Object onClose(WsRequestPacket webSocketPacket, byte[] bytes, ImChannelContext imChannelContext) throws Exception {
		JimServerAPI.remove(imChannelContext, "receive close flag");
		return null;
	}

	public WsMsgHandler(WsConfig wsServerConfig, String[] scanPackages) {
		this.wsServerConfig = null;
		this.setWsServerConfig(wsServerConfig);
	}

	public WsMsgHandler() {
		this(WsConfig.newBuilder().build(), (String[])null);
	}

	public WsConfig getWsServerConfig() {
		return this.wsServerConfig;
	}

	public void setWsServerConfig(WsConfig wsServerConfig) {
		this.wsServerConfig = wsServerConfig;
	}
}
